<template>
  <div v-if="proxy.isAuth(['ROOT'])">
    <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="form">
      <el-form-item>
        <el-button
            type="primary"
            :disabled="!proxy.isAuth(['ROOT'])"
            @click="addHandle()"
        >新增角色</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="dataForm.roleList"
        :header-cell-style="{ background: '#f5f57fa' }"
        border
        v-loading="data.loading"
    >

      <el-table-column
          type="index"
          header-align="center"
          align="center"
          min-width="60"
          label="序号"
      >
        <template #default="scope">
          <span>{{
              (data.pageIndex - 1) * data.pageSize + scope.$index + 1
            }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="roleName"
          header-align="center"
          align="center"
          min-width="80"
          label="角色名称"
      >
      </el-table-column>
      <el-table-column
          prop="roleDesc"
          header-align="center"
          align="center"
          min-width="80"
          label="角色描述"
      >
      </el-table-column>
      <el-table-column
          header-align="center"
          align="center"
          min-width="80"
          label="模块权限"
      >
        <template #default="scope">
          <el-tag
              v-for="item in scope.row.moduleList"
              :key="item.id"
              style="margin-right: 5px; margin-bottom: 5px;"
          >
            {{ item.moduleName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          header-align="center"
          align="center"
          width="180"
          label="操作"
      >
        <template #default="scope">
          <el-button
              type="success" text class="btn-width"
              v-if="proxy.isAuth(['ROOT'])"
              @click="getDetailHandle(scope.row.id)"
          >
            查看
          </el-button>
          <el-button
              type="primary" text class="btn-width"
              v-if="proxy.isAuth(['ROOT'])"
              @click="updateHandle(scope.row)"
          >
            修改
          </el-button>
          <el-button
              type="danger" text class="btn-width"
              v-if="proxy.isAuth(['ROOT'])"
              :disabled="scope.row.root"
              @click="deleteHandle(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog
      :title="!dialog.dataForm.id ? '新增' : '修改'"
      v-if="proxy.isAuth(['ROOT'])"
      :close-on-click-modal="false"
      v-model="dialog.visible"
      width="450px"
  >
    <el-form
        :model="dialog.dataForm"
        ref="dialogForm"
        :rules="dialog.dataRule"
        label-width="80px"
    >
      <el-form-item label="角色名" prop="roleName">
        <el-input v-model="dialog.dataForm.roleName" maxlength="20" clearable />
      </el-form-item>
      <el-form-item label="描述" prop="roleDesc">
        <el-input v-model="dialog.dataForm.roleDesc" maxlength="20" clearable />
      </el-form-item>
      <el-form-item label="权限" prop="deptId">
        <el-tree
            :data="dialog.dataForm.permissionList"
            show-checkbox
            node-key="id"
            :props="{ label: 'label' }"
            @check="handleCheck"
            ref="permissionTree"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-input">
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSumbit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
const { proxy } = getCurrentInstance();
import { dayjs } from "element-plus";

const dataForm = reactive({
  roleName: "",
  roleList: []
});
const dataRule = reactive({

});
const data = reactive({
  dataList: [],
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  loading: false
});
const dialog = reactive({
  visible: false,
  update: false,
  dataForm: {
    id: null,
    roleName: null,
    roleDesc: null,
    permissionList: [],
    selectedPermissions: [],
  },
  dataRule: {
    roleName: [
      {
        required: false,
        pattern: "^[\u4e00-\u9fa5]{1,10}$",
        message: "角色名称格式错误",
      },
    ]
  },
});

// 处理选中/取消选中
function handleCheck(checkedNode, checkedStatus) {
  // 获取所有选中的节点（包括半选状态）
  const allSelectedNodes = [
    ...checkedStatus.checkedNodes,
    ...checkedStatus.halfCheckedNodes
  ];
  // 过滤出权限节点（排除模块节点）
  const selectedPermissions = allSelectedNodes
      .filter(node => node.id && node.moduleId) // 确保是权限节点（不是模块）
      .map(node => ({
        id: node.id,
        permissionName: node.label,
        moduleId: node.moduleId,
      }));

  // 更新选中的权限
  dialog.dataForm.permissions = JSON.stringify(selectedPermissions.map(permission => permission.id));
}

// 获取最终选中的权限（格式化为 [{id, permissionName, moduleId, actionId}, ...]）
function getSelectedPermissions() {
  const selectedPermissionIds = dialog.dataForm.selectedPermissions;
  const result = [];
  dialog.dataForm.permissionList.forEach(module => {
    if (module.children) {
      module.children.forEach(permission => {
        if (selectedPermissionIds.includes(permission.id)) {
          result.push({
            id: permission.id,
            permissionName: permission.label,
            moduleId: module.id,
            actionId: permission.actionId
          });
        }
      });
    }
  });

  return result;
}
function loadRoleList() {
  proxy.$http("/mis/role/searchAllRole", "GET", null, true, (resp) => {
    dataForm.roleList = resp.list;
  });
}
function loadPermissionList() {
  proxy.$http("/mis/permission/searchAllModuleAndPermission", "GET", null, true, (resp) => {
    dialog.dataForm.permissionList = resp.permissionList.map(module => ({
      id: module.id,
      label: module.moduleName,
      children: module.permissionList.map(permission => ({
        id: permission.id,
        label: permission.permissionName,
        moduleId: module.id,
        actionId: permission.actionId
      }))
    }));
  });
}
// 执行两个封装函数
loadRoleList();


// 添加管理人员
function addHandle() {
  dialog.dataForm.id = null;
  loadPermissionList();
  dialog.update = false;
  dialog.visible = true;
  // 清空dialogForm控件
  proxy.$nextTick(() => {
    proxy.$refs['dialogForm'].resetFields();
  })
}

// 数据表单提交
function dataFormSumbit() {
  // 验证表单信息是否有效
  proxy.$refs['dialogForm'].validate(valid => {
    // console.log("表单提交中的valid：" + valid);
    if(valid) {
      let json = {
        id: dialog.dataForm.id,
        roleName: dialog.dataForm.roleName,
        roleDesc: dialog.dataForm.roleDesc,
        permissions: dialog.dataForm.permissions,
        systemic: 0, // 非系统内置
      };
      proxy.$http(`/mis/role/${dialog.dataForm.id == null ? 'insert' : 'update'}`, 'POST', json, true, resp => {
        if(resp.code == 200) {
          proxy.$message({
            message: '操作成功',
            type: 'success',
            duration: 1200,
            // 关闭时触发事件
            onClose: () => {
              dialog.visible = false;
              loadRoleList();
            }
          });
        } else {
          // 报错
          proxy.$message({
            message: '操作失败',
            type: 'error',
            duration: 1200
          });
        }
      })
    }
  })
}

function getDetailHandle(id) {

}

function updateHandle(row) {
  loadPermissionList();
  dialog.dataForm.selectedPermissions
  console.log("row: ", row.permissions);
  dialog.dataForm = row;
  dialog.update = true;
  dialog.visible = true;
}

// function selectable(row, index) {
//
//   // console.log("row:" + JSON.stringify(row));
//   let temp = row.roles.split(", ")
//   if(temp.includes("超级管理员")) {
//     return false;
//   }
//   return true;
// }

function deleteHandle(id) {
  // 如果 id = 5 并且 data.selections = [{id: 1}, {id: 2}, {id: 3}]，则 ids = [5]。
  // 如果 id = null 并且 data.selections = [{id: 1}, {id: 2}, {id: 3}]，则 ids = [1, 2, 3]
  let ids = id ? [id] : data.selections.map(item => {
    return item.id;
  });
  if(ids.length == 0) {
    proxy.$message({
      message: '没有选中记录',
      type: 'warning',
      duration: 1200
    });
  } else {
    proxy.$confirm('确定要删除选中的记录？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
        .then(() => {
          proxy.$http('/mis/user/deleteByIds', 'POST', {ids: ids}, true, resp => {
            if(resp.rows > 0) {
              proxy.$message({
                message: '删除成功',
                type: 'success',
                duration: 1200,
                onClose: () => {
                  loadRoleList();
                }
              });
            } else {
              proxy.$message({
                message: '删除失败',
                type: 'warning',
                duration: 1200
              });
            }
          })
        })
  }
}

</script>

<style scoped lang="less">
@import url(../style.less);
.input {
  width: 110px;
}
.dialog-input {
  width: 100% !important;
}
.btn-width {
  width: 25px;
}
</style>